package com.tz.dao.impl;

import com.tz.dao.IAccountDao;
import com.tz.entity.Account;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by yejf on 2017/1/10.
 */
@Repository  //被标记为dao组件
@Transactional
public class AccountDaoImpl implements IAccountDao {

    @Autowired
    private SessionFactory factory;

    public AccountDaoImpl() {
    }

    public void setFactory(SessionFactory factory) {
        this.factory = factory;
    }

    //获取Session
    private Session getSession() {
        return factory == null ? null : factory.getCurrentSession();
    }

    @Override
    public void save(Account account) {
        getSession().save(account);
    }

    @Override
    public void update(Account account) {
        getSession().update(account);
    }

    @Override
    public Account find(Long id) {
        return (Account)getSession().get(Account.class,id);
    }

    @Override
    public List<Account> findAll() {
        return (List<Account>)getSession().createQuery("from Account as a").list();
    }

    @Override
    public Account findByNo(String no) {
        return (Account)getSession().createCriteria(Account.class,"a")
                        .add(Restrictions.eq("a.no", no))
                        .uniqueResult();
    }

}
